<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备二维码生成工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }

        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
        }

        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }

        input[type="text"],
        input[type="number"],
        textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        input[type="text"]:focus,
        input[type="number"]:focus,
        textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: 500;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5568d3;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .btn-success {
            background: #48bb78;
            color: white;
        }

        .btn-success:hover {
            background: #38a169;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        .result {
            margin-top: 30px;
            padding: 20px;
            background: #f7fafc;
            border-radius: 8px;
            border: 2px solid #e0e0e0;
        }

        .result h3 {
            color: #333;
            margin-bottom: 15px;
        }

        .qr-info {
            margin: 15px 0;
        }

        .qr-info strong {
            color: #667eea;
        }

        .qr-url {
            background: white;
            padding: 10px;
            border-radius: 4px;
            word-break: break-all;
            margin-top: 5px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }

        .alert {
            padding: 12px 16px;
            border-radius: 6px;
            margin-bottom: 20px;
        }

        .alert-info {
            background: #e6f7ff;
            border: 1px solid #91d5ff;
            color: #0050b3;
        }

        .alert-success {
            background: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #389e0d;
        }

        .alert-error {
            background: #fff1f0;
            border: 1px solid #ffa39e;
            color: #cf1322;
        }

        .help-text {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }

        #qrCanvas {
            margin-top: 20px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
        }

        .batch-input {
            min-height: 100px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>🔧 设备二维码生成工具</h1>
        <p class="subtitle">为设备生成专属二维码，扫码后直接进入报修页面</p>

        <div class="alert alert-info">
            <strong>使用说明：</strong> 输入资产ID和域名，点击生成后会创建二维码URL。用户扫描此二维码即可自动跳转到对应设备的报修页面。
        </div>

        <!-- 单个生成 -->
        <div class="form-group">
            <label for="assetId">资产ID</label>
            <input type="number" id="assetId" placeholder="例如: 1">
            <p class="help-text">请输入要生成二维码的设备资产ID</p>
        </div>

        <div class="form-group">
            <label for="domain">小程序关联域名</label>
            <input type="text" id="domain" placeholder="例如: https://yourdomain.com" value="https://yourdomain.com">
            <p class="help-text">请输入您在微信公众平台配置的业务域名（需要已备案）</p>
        </div>

        <div class="form-group">
            <label for="adminKey">管理员密钥</label>
            <input type="text" id="adminKey" placeholder="输入管理员密钥" value="repair2024admin">
            <p class="help-text">用于验证权限的管理员密钥</p>
        </div>

        <div class="form-group">
            <label for="apiUrl">后端API地址</label>
            <input type="text" id="apiUrl" placeholder="例如: http://localhost:3000" value="http://localhost:3000">
            <p class="help-text">后端API服务器地址（如果是本机访问用localhost，外网访问用自己IP）</p>
        </div>

        <div class="btn-group">
            <button class="btn btn-primary" onclick="generateQRCode()">生成二维码</button>
            <button class="btn btn-success" onclick="downloadQRCode()" id="downloadBtn"
                style="display:none;">下载二维码</button>
        </div>

        <!-- 结果显示区域 -->
        <div id="result" style="display:none;" class="result">
            <h3>✅ 生成成功</h3>
            <div class="qr-info">
                <strong>资产ID:</strong> <span id="resultAssetId"></span>
            </div>
            <div class="qr-info">
                <strong>二维码URL:</strong>
                <div class="qr-url" id="resultUrl"></div>
            </div>
            <div class="qr-info">
                <strong>二维码图片:</strong>
                <div id="qrCodeContainer"></div>
            </div>
        </div>

        <!-- 批量生成 -->
        <div style="margin-top: 40px; padding-top: 30px; border-top: 2px solid #e0e0e0;">
            <h2 style="margin-bottom: 20px; color: #333;">批量生成</h2>
            <div class="form-group">
                <label for="assetIds">资产ID列表（每行一个）</label>
                <textarea id="assetIds" class="batch-input" placeholder="1&#10;2&#10;3&#10;4&#10;5"></textarea>
                <p class="help-text">每行输入一个资产ID</p>
            </div>
            <button class="btn btn-primary" onclick="batchGenerate()">批量生成</button>
            <div id="batchResult" style="margin-top: 20px;"></div>
        </div>
    </div>

    <!-- 引入QRCode.js库 -->
    <script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>

    <script>
        let currentQRCode = null;

        async function generateQRCode() {
            const assetId = document.getElementById('assetId').value.trim();
            const domain = document.getElementById('domain').value.trim();
            const adminKey = document.getElementById('adminKey').value.trim();
            const apiUrl = document.getElementById('apiUrl').value.trim();

            if (!assetId) {
                alert('请输入资产ID');
                return;
            }

            if (!domain) {
                alert('请输入域名');
                return;
            }

            try {
                // 调用后端API生成二维码URL
                const response = await fetch(`${apiUrl}/api/qrcode/generate`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        assetId: parseInt(assetId),
                        domain: domain,
                        adminKey: adminKey
                    })
                });

                const result = await response.json();

                if (result.success && result.data) {
                    const qrCodeUrl = result.data.qrCodeUrl;

                    // 显示结果
                    document.getElementById('resultAssetId').textContent = assetId;
                    document.getElementById('resultUrl').textContent = qrCodeUrl;
                    document.getElementById('result').style.display = 'block';
                    document.getElementById('downloadBtn').style.display = 'inline-block';

                    // 清除旧的二维码
                    const qrContainer = document.getElementById('qrCodeContainer');
                    qrContainer.innerHTML = '<div id="qrcode"></div>';

                    // 生成新的二维码
                    currentQRCode = new QRCode(document.getElementById('qrcode'), {
                        text: qrCodeUrl,
                        width: 256,
                        height: 256,
                        colorDark: '#000000',
                        colorLight: '#ffffff',
                        correctLevel: QRCode.CorrectLevel.H
                    });

                    alert('二维码生成成功！');
                } else {
                    alert('生成失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('生成失败:', error);
                alert('生成失败: ' + error.message);
            }
        }

        function downloadQRCode() {
            const canvas = document.querySelector('#qrcode canvas');
            if (canvas) {
                const url = canvas.toDataURL('image/png');
                const link = document.createElement('a');
                const assetId = document.getElementById('assetId').value;
                link.download = `asset-${assetId}-qrcode.png`;
                link.href = url;
                link.click();
            }
        }

        async function batchGenerate() {
            const assetIdsText = document.getElementById('assetIds').value.trim();
            const domain = document.getElementById('domain').value.trim();
            const adminKey = document.getElementById('adminKey').value.trim();
            const apiUrl = document.getElementById('apiUrl').value.trim();

            if (!assetIdsText) {
                alert('请输入资产ID列表');
                return;
            }

            if (!domain) {
                alert('请输入域名');
                return;
            }

            const assetIds = assetIdsText.split('\n')
                .map(id => id.trim())
                .filter(id => id)
                .map(id => parseInt(id));

            if (assetIds.length === 0) {
                alert('没有有效的资产ID');
                return;
            }

            try {
                const response = await fetch(`${apiUrl}/api/qrcode/generate-batch`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        assetIds: assetIds,
                        domain: domain,
                        adminKey: adminKey
                    })
                });

                const result = await response.json();

                if (result.success && result.data) {
                    let html = '<div class="alert alert-success">批量生成完成！</div>';
                    html += '<table style="width: 100%; border-collapse: collapse; margin-top: 10px;">';
                    html += '<tr style="background: #f0f0f0;"><th style="padding: 10px; border: 1px solid #ddd;">资产ID</th><th style="padding: 10px; border: 1px solid #ddd;">状态</th><th style="padding: 10px; border: 1px solid #ddd;">二维码URL</th></tr>';

                    result.data.results.forEach(item => {
                        const statusColor = item.status === 'success' ? '#52c41a' : '#f5222d';
                        html += `<tr>
                            <td style="padding: 10px; border: 1px solid #ddd;">${item.assetId}</td>
                            <td style="padding: 10px; border: 1px solid #ddd; color: ${statusColor};">${item.status === 'success' ? '✓ 成功' : '✗ 失败'}</td>
                            <td style="padding: 10px; border: 1px solid #ddd; font-size: 11px; word-break: break-all;">${item.qrCodeUrl || item.message || '-'}</td>
                        </tr>`;
                    });

                    html += '</table>';
                    document.getElementById('batchResult').innerHTML = html;
                } else {
                    alert('批量生成失败: ' + (result.message || '未知错误'));
                }
            } catch (error) {
                console.error('批量生成失败:', error);
                alert('批量生成失败: ' + error.message);
            }
        }
    </script>
</body>

</html>